package com.mbl.base.modular.mall.task;

import com.mbl.base.core.common.constant.SpringContextHolder;
import com.mbl.base.core.modular.task.Task;
import com.mbl.base.modular.mall.entity.Order;
import com.mbl.base.modular.mall.entity.OrderGoods;
import com.mbl.base.modular.mall.service.IGoodsProductService;
import com.mbl.base.modular.mall.service.IOrderGoodsService;
import com.mbl.base.modular.mall.service.IOrderService;
import com.mbl.base.modular.mall.utils.OrderUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.time.LocalDateTime;
import java.util.List;

public class OrderUnpaidTask extends Task {
    private final Log logger = LogFactory.getLog(OrderUnpaidTask.class);
    private long orderId = -1;

    public OrderUnpaidTask(Integer orderId, long delayInMilliseconds){
        super("OrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderUnpaidTask(Long orderId){
        super("OrderUnpaidTask-" + orderId, 30 * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---订单超时未付款---" + this.orderId);
        IOrderService orderService = SpringContextHolder.getBean(IOrderService.class);
        IOrderGoodsService orderGoodsService = SpringContextHolder.getBean(IOrderGoodsService.class);
        IGoodsProductService goodsProductService = SpringContextHolder.getBean(IGoodsProductService.class);
        Order order = orderService.getById(this.orderId);
        if(order == null){
            return;
        }
        if(!OrderUtil.isCreateStatus(order)){
            return;
        }

        // 设置订单已取消状态
        order.setOrderStatus(Integer.valueOf(OrderUtil.STATUS_AUTO_CANCEL));
        order.setEndTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }

        // 商品货品数量增加
        Long orderId = order.getId();
        List<OrderGoods> orderGoodsList = orderGoodsService.queryByOrderid(orderId);
        for (OrderGoods orderGoods : orderGoodsList) {
            Long productId = orderGoods.getProductId();
            Integer number = orderGoods.getNumber();
            if (goodsProductService.addStock(productId, number) == 0) {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }
        logger.info("系统结束处理延时任务---订单超时未付款---" + this.orderId);
    }
}
